package com.newcoin.xgb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.newcoin.xgb.dto.RegisteredDto;
import com.newcoin.xgb.entity.Result;
import com.newcoin.xgb.entity.XgbAppVersion;
import com.newcoin.xgb.entity.XgbUsers;
import com.newcoin.xgb.mapper.AppVersionMapper;
import com.newcoin.xgb.mapper.UsersMapper;
import com.newcoin.xgb.service.XgbAccountService;
import com.newcoin.xgb.service.XgbWebService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class XgbWebServiceImpl implements XgbWebService {

    @Autowired
    private UsersMapper mapper;

    @Value("${defaultHeadPath}")
    private String defaultHeadPath;

    @Autowired
    private XgbAccountService service;

    @Value("${downloadAppUrl}")
    private String downloadAppUrl;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result registered(RegisteredDto registeredDto) throws Exception {
        log.info("registeredDto={}", registeredDto);
        String redisCode = redisTemplate.opsForValue().get("send" + registeredDto.getMobile());
        Result result = new Result();
        if (StringUtils.isEmpty(redisCode)) {
            result.setCode(500);
            result.setMessage("验证码不存在");
            return result;
        }
        if (!redisCode.equalsIgnoreCase(registeredDto.getVerCode())) {
            result.setCode(500);
            result.setMessage("验证码不正确");
            return result;
        }
        QueryWrapper<XgbUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", registeredDto.getMobile());
        XgbUsers users = mapper.selectOne(queryWrapper);
        if (users != null) {
            result.setCode(500);
            result.setMessage("该号码已注册");
            return result;
        }
        users = new XgbUsers();
        users.setInvCode(createInviteCode());
        users.setLoginPwd(DigestUtils.md5DigestAsHex(registeredDto.getPassword().getBytes()));
        users.setMobile(registeredDto.getMobile());
        users.setNickname(registeredDto.getMobile());
        users.setHeadPath(defaultHeadPath);
        if (!StringUtils.isEmpty(registeredDto.getInvCode())) {
            QueryWrapper<XgbUsers> pQueryWrapper = new QueryWrapper<>();
            pQueryWrapper.eq("inv_code", registeredDto.getInvCode());
            XgbUsers pUser = mapper.selectOne(pQueryWrapper);
            if (pUser == null) {
                result.setCode(500);
                result.setMessage("推荐人不存在");
                return result;
            }
            users.setPid(pUser.getId());
            users.setPath(pUser.getPath() == null ? "," + pUser.getId() : pUser.getPath() + "," + pUser.getId());
            XgbUsers finalUsers = users;
            UpdateWrapper<XgbUsers> usersUpdateWrapper = new UpdateWrapper<>();
            usersUpdateWrapper.eq("id", pUser.getId()).setSql("direct_push_num=direct_push_num+1");
            int row = mapper.update(null, usersUpdateWrapper);
            log.info("增加直推人数:" + row);
            UpdateWrapper<XgbUsers> usersUpdateWrapper1 = new UpdateWrapper<>();
            usersUpdateWrapper1.setSql("team_num=team_num+1")
                    .last("WHERE id IN (" + finalUsers.getPath().substring(finalUsers.getPath().indexOf(",") + 1) + ")");
            row = row + mapper.update(null, usersUpdateWrapper1);
            log.info("增加团队人数:" + --row);//(row-1)
        }
        users.setRegDate(new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date()));
        int row = mapper.insert(users);
        row = row + service.createAccount(users.getId());
        if (row != 2) {
            result.setMessage("注册失败");
            result.setCode(500);
            return result;
        }
        result.setCode(200);
        result.setMessage("注册成功");
        result.setData(downloadAppUrl);
        return result;
    }

    private String createInviteCode() {
        String newInviteCode = RandomStringUtils.randomAlphanumeric(6).toUpperCase();
        QueryWrapper<XgbUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("inv_code", newInviteCode);
        XgbUsers users = mapper.selectOne(queryWrapper);
        if (users != null) {
            return createInviteCode();
        }
        return newInviteCode;
    }

}
